#include "GlobalConfig.h"

GlobalConfig& GlobalConfig::getInstance() {
    static GlobalConfig instance;
    return instance;
}

GlobalConfig::GlobalConfig()
    : wifiSSID("esp8266"),
      wifiPassword("esp8266"),
      mqttServer("qf9ea91d.ala.cn-hangzhou.emqxsl.cn"),
      mqttSSLCA(R"EOF(
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
        MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
        QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
        b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
        nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
        BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
        TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
        hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
        YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
        CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
        -----END CERTIFICATE-----
)EOF"),
      mqttPort("8883"),
      mqttClientId("esp8266"),
      mqttUser("test"),
      mqttPassword("123456"),
      mqttTopicControl("esp8266-TopicControl"),
      mqttTopicStatus("esp8266-TopicStatus"),
      mqttTopicTimer("6"),
      mqttTopicResetTimer("6"),
      httpApiUrl("esp8266"),
      mqttSSLCAOpen("0"),
      httpApiType("1"),
      wifiErrSec(0),
      wifiErrSecOpenWebConf(10),
      webServerEndSecSet(15),
      webServerEndSec(0),
      mqttErrSec(0),
      mqttErrSecOpenWebConf(1),
      startTime(0),
      endTime(0),
      switchStatus(false) {}

GlobalConfig::~GlobalConfig() {}

// Getter 和 Setter 函数保持不变
// WiFi 相关配置的 getter 和 setter 实现
std::string GlobalConfig::getWifiSsid() const {
    return wifiSSID;
}
void GlobalConfig::setWifiSsid(const std::string& wifiSsid) {
    this->wifiSSID = wifiSsid;
}
std::string GlobalConfig::getWifiPassword() const {
    return wifiPassword;
}
void GlobalConfig::setWifiPassword(const std::string& wifiPassword) {
    this->wifiPassword = wifiPassword;
}

// MQTT 相关配置的 getter 和 setter 实现
std::string GlobalConfig::getMqttServer() const {
    return mqttServer;
}
void GlobalConfig::setMqttServer(const std::string& mqttServer) {
    this->mqttServer = mqttServer;
}
std::string GlobalConfig::getMqttSslca() const {
    return mqttSSLCA;
}
void GlobalConfig::setMqttSslca(const std::string& mqttSslca) {
    this->mqttSSLCA = mqttSslca;
}
std::string GlobalConfig::getMqttPort() const {
    return mqttPort;
}
void GlobalConfig::setMqttPort(const std::string& mqttPort) {
    this->mqttPort = mqttPort;
}
std::string GlobalConfig::getMqttClientId() const {
    return mqttClientId;
}
void GlobalConfig::setMqttClientId(const std::string& mqttClientId) {
    this->mqttClientId = mqttClientId;
}
std::string GlobalConfig::getMqttUser() const {
    return mqttUser;
}
void GlobalConfig::setMqttUser(const std::string& mqttUser) {
    this->mqttUser = mqttUser;
}
std::string GlobalConfig::getMqttPassword() const {
    return mqttPassword;
}
void GlobalConfig::setMqttPassword(const std::string& mqttPassword) {
    this->mqttPassword = mqttPassword;
}
std::string GlobalConfig::getMqttTopicControl() const {
    return mqttTopicControl;
}
void GlobalConfig::setMqttTopicControl(const std::string& mqttTopicControl) {
    this->mqttTopicControl = mqttTopicControl;
}
std::string GlobalConfig::getMqttTopicStatus() const {
    return mqttTopicStatus;
}
void GlobalConfig::setMqttTopicStatus(const std::string& mqttTopicStatus) {
    this->mqttTopicStatus = mqttTopicStatus;
}
std::string GlobalConfig::getMqttTopicTimer() const {
    return mqttTopicTimer;
}
void GlobalConfig::setMqttTopicTimer(const std::string& mqttTopicTimer) {
    this->mqttTopicTimer = mqttTopicTimer;
}
std::string GlobalConfig::getMqttTopicResetTimer() const {
    return mqttTopicResetTimer;
}
void GlobalConfig::setMqttTopicResetTimer(const std::string& mqttTopicResetTimer) {
    this->mqttTopicResetTimer = mqttTopicResetTimer;
}

// HTTP 相关配置的 getter 和 setter 实现
std::string GlobalConfig::getHttpApiUrl() const {
    return httpApiUrl;
}
void GlobalConfig::setHttpApiUrl(const std::string& httpApiUrl) {
    this->httpApiUrl = httpApiUrl;
}
std::string GlobalConfig::getMqttSslcaOpen() const {
    return mqttSSLCAOpen;
}
void GlobalConfig::setMqttSslcaOpen(const std::string& mqttSslcaOpen) {
    this->mqttSSLCAOpen = mqttSslcaOpen;
}
std::string GlobalConfig::getHttpApiType() const {
    return httpApiType;
}
void GlobalConfig::setHttpApiType(const std::string& httpApiType) {
    this->httpApiType = httpApiType;
}

// 错误次数和时间配置的 getter 和 setter 实现
unsigned int GlobalConfig::getWifiErrSec() const {
    return wifiErrSec;
}

void GlobalConfig::setWifiErrSec(const unsigned int& wifiErrSec) {
    this->wifiErrSec = wifiErrSec;
}
unsigned int GlobalConfig::getWifiErrSecOpenWebConf() const {
    return wifiErrSecOpenWebConf;
}
void GlobalConfig::setWifiErrSecOpenWebConf(const unsigned int&  wifiErrSecOpenWebConf) {
    this->wifiErrSecOpenWebConf = wifiErrSecOpenWebConf;
}
unsigned int GlobalConfig::getWebServerEndSecSet() const {
    return webServerEndSecSet;
}
void GlobalConfig::setWebServerEndSecSet(const unsigned int&  webServerEndSecSet) {
    this->webServerEndSecSet = webServerEndSecSet;
}
unsigned int GlobalConfig::getWebServerEndSec() const {
    return webServerEndSec;
}
void GlobalConfig::setWebServerEndSec(const unsigned int&  webServerEndSec) {
    this->webServerEndSec = webServerEndSec;
}
unsigned int GlobalConfig::getMqttErrSec() const {
    return mqttErrSec;
}
void GlobalConfig::setMqttErrSec(const unsigned int&  mqttErrSec) {
    this->mqttErrSec = mqttErrSec;
}
unsigned int GlobalConfig::getMqttErrSecOpenWebConf() const {
    return mqttErrSecOpenWebConf;
}
void GlobalConfig::setMqttErrSecOpenWebConf(const unsigned int&  mqttErrSecOpenWebConf) {
    this->mqttErrSecOpenWebConf = mqttErrSecOpenWebConf;
}

// 定时开关时间的 getter 和 setter 实现
unsigned long GlobalConfig::getStartTime() const {
    return startTime;
}
void GlobalConfig::setStartTime(const unsigned long& startTime) {
    this->startTime = startTime;
}
unsigned long GlobalConfig::getEndTime() const {
    return endTime;
}
void GlobalConfig::setEndTime(const unsigned long& endTime) {
    this->endTime = endTime;
}

// 开关状态的 getter 和 setter 实现
bool GlobalConfig::isSwitchStatus() const {
    return switchStatus;
}
void GlobalConfig::setSwitchStatus(const bool& switchStatus) {
    this->switchStatus = switchStatus;
}

void GlobalConfig::readConfig() {
    if (!LittleFS.begin()) {  // 使用LittleFS初始化
        debugLog("Failed to start LittleFS\n");
        return;
    }

    if (!LittleFS.exists("/config.json")) {  // 使用LittleFS检查文件是否存在
        debugLog("Config file does not exist\n");
        LittleFS.end();  // 使用LittleFS关闭文件系统
        return;
    }

    File configFile = LittleFS.open("/config.json", "r");  // 使用LittleFS打开文件
    if (!configFile) {
        debugLog("Failed to open config file for reading\n");
        LittleFS.end();
        return;
    }

    size_t size = configFile.size();
    std::unique_ptr<char[]> buf(new char[size]);
    if (configFile.readBytes(buf.get(), size) != size) {
        debugLog("Failed to read config file\n");
        configFile.close();
        LittleFS.end();
        return;
    }

    DynamicJsonDocument  doc(1024);
    DeserializationError error = deserializeJson(doc, buf.get());
    if (error) {
        debugLog("JSON deserialization failed: %s\n", error.c_str());
        configFile.close();
        LittleFS.end();
        return;
    }

    wifiSSID = doc["wifiSSID"].as<std::string>();
    wifiPassword = doc["wifiPassword"].as<std::string>();
    mqttServer = doc["mqttServer"].as<std::string>();
    mqttSSLCA = doc["mqttSSLCA"].as<std::string>();
    mqttPort = doc["mqttPort"].as<std::string>();
    mqttClientId = doc["mqttClientId"].as<std::string>();
    mqttUser = doc["mqttUser"].as<std::string>();
    mqttPassword = doc["mqttPassword"].as<std::string>();
    mqttTopicControl = doc["mqttTopicControl"].as<std::string>();
    mqttTopicStatus = doc["mqttTopicStatus"].as<std::string>();
    mqttTopicTimer = doc["mqttTopicTimer"].as<std::string>();
    mqttTopicResetTimer = doc["mqttTopicResetTimer"].as<std::string>();
    httpApiUrl = doc["httpApiUrl"].as<std::string>();
    startTime = doc["startTime"].as<unsigned long>();
    endTime = doc["endTime"].as<unsigned long>();
    mqttSSLCAOpen = doc["mqttSSLCAOpen"].as<std::string>();
    httpApiType = doc["httpApiType"].as<std::string>();
    wifiErrSec = doc["wifiErrSec"].as<unsigned int>();
    wifiErrSecOpenWebConf = doc["wifiErrSecOpenWebConf"].as<unsigned int>();
    webServerEndSecSet = doc["webServerEndSecSet"].as<unsigned int>();
    webServerEndSec = doc["webServerEndSec"].as<unsigned int>();
    mqttErrSec = doc["mqttErrSec"].as<unsigned int>();
    mqttErrSecOpenWebConf = doc["mqttErrSecOpenWebConf"].as<unsigned int>();
    switchStatus = doc["switchStatus"].as<bool>();

    configFile.close();
    LittleFS.end();
}

void GlobalConfig::saveConfig() {
    if (!LittleFS.begin()) {  // 使用LittleFS初始化
        debugLog("Failed to start LittleFS\n");
        return;
    }

    File configFile = LittleFS.open("/config.json", "w");  // 使用LittleFS打开文件用于写入
    if (!configFile) {
        debugLog("Failed to open config file for writing\n");
        LittleFS.end();  // 使用LittleFS关闭文件系统
        return;
    }

    DynamicJsonDocument doc(1024);
    doc["wifiSSID"] = wifiSSID;
    doc["wifiPassword"] = wifiPassword;
    doc["mqttServer"] = mqttServer;
    doc["mqttSSLCA"] = mqttSSLCA;
    doc["mqttPort"] = mqttPort;
    doc["mqttClientId"] = mqttClientId;
    doc["mqttUser"] = mqttUser;
    doc["mqttPassword"] = mqttPassword;
    doc["mqttTopicControl"] = mqttTopicControl;
    doc["mqttTopicStatus"] = mqttTopicStatus;
    doc["mqttTopicTimer"] = mqttTopicTimer;
    doc["mqttTopicResetTimer"] = mqttTopicResetTimer;
    doc["httpApiUrl"] = httpApiUrl;
    doc["startTime"] = startTime;
    doc["endTime"] = endTime;
    doc["mqttSSLCAOpen"] = mqttSSLCAOpen;
    doc["httpApiType"] = httpApiType;
    doc["wifiErrSec"] = wifiErrSec;
    doc["wifiErrSecOpenWebConf"] = wifiErrSecOpenWebConf;
    doc["webServerEndSecSet"] = webServerEndSecSet;
    doc["webServerEndSec"] = webServerEndSec;
    doc["mqttErrSec"] = mqttErrSec;
    doc["mqttErrSecOpenWebConf"] = mqttErrSecOpenWebConf;
    doc["switchStatus"] = switchStatus;

    if (serializeJson(doc, configFile) == 0) {
        debugLog("Failed to write to config file\n");
    }
    configFile.close();
    LittleFS.end();
}